package com.zp.common.pdf;

import org.apache.pdfbox.multipdf.PDFMergerUtility;

import java.io.File;
import java.io.IOException;

/**
 * <p>
 *
 * </p>
 *
 * @author zp
 * @since 2019/9/2
 */
public class MergeFile {
    /**
     * 获取文件夹下面的所有文件
     *
     * @param folder
     * @return
     * @throws IOException
     */
    private static String[] getFiles (String folder) throws IOException {
        File _folder = new File(folder);
        String[] filesInFolder;

        if (_folder.isDirectory()) {
            filesInFolder = _folder.list();
            return filesInFolder;
        } else {
            throw new IOException("Path is not a directory");
        }
    }

    /**
     * 合并pdf
     *
     * @param folder
     * @param desPath
     * @throws IOException
     */
    public static void mergePdf (String folder, String desPath) throws IOException {
        //pdf合并工具类
        PDFMergerUtility mergePdf = new PDFMergerUtility();

        String destinationFileName = desPath;

        String[] filesInFolder = getFiles(folder);

        for (int i = 0; i < filesInFolder.length; i++) {
            //循环添加要合并的pdf存放的路径
            mergePdf.addSource(folder + "/" + filesInFolder[i]);
        }
        //设置合并生成pdf文件名称
        mergePdf.setDestinationFileName(folder + "/" + destinationFileName);
        //合并pdf
        mergePdf.mergeDocuments();
    }

    public static void main (String[] args) throws IOException {

        String folder = "D:/diagnose/merge";
        String destinationFileName = "mergedTest.pdf";
        mergePdf(folder, destinationFileName);
    }
}
